package cn.rui.service;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.rui.common.ContentBean;
import cn.rui.common.ResponseBean;
import cn.rui.error.DisableException;
import cn.rui.mapper.UserMapper;
import cn.rui.pojo.User;
import cn.rui.pojo.vo.PageVo;
import cn.rui.pojo.vo.UpdatePassVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 徽州大都督
 * @date 2021/6/8
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class UserService extends ServiceImpl<UserMapper,User> {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AsyncService asyncService;

    public ResponseBean login(String username, String password, HttpSession session) {

        QueryWrapper<User> wrapper = new QueryWrapper<> ();
        wrapper.eq ("username", username);
        User user = userMapper.selectOne (wrapper);

        if (!ObjectUtils.isEmpty (user)) {
            //密码错误
            if (!user.getPassword ().equals (password)) {
                //保存登录日志
                asyncService.saveLoginLog (ContentBean.AccountPassEroor, username, 0);
                return ResponseBean.error (ContentBean.AccountPassEroor, 401);
            }

            //账号禁用
            if (user.getStatus () == 1) {
                //保存登录日志
                asyncService.saveLoginLog (ContentBean.AccountDisabled, username, 0);
                throw new DisableException (ContentBean.AccountDisabled);
            }

            //将用户名存到session中
            session.setAttribute ("username", username);

            //保存登录日志
            asyncService.saveLoginLog (ContentBean.LoginSuccess, username, 1);

            //更新登录时间
            user.setUpdateTime (new Date ());

            userMapper.updateById (user);
            StpUtil.setLoginId (user.getUsername ());
            SaTokenInfo tokenInfo = StpUtil.getTokenInfo ();

            Map map = new HashMap ();
            map.put ("user", user);
            map.put ("tokenInfo", tokenInfo);

            return ResponseBean.success (ContentBean.LoginSuccess, map);
        }
        return ResponseBean.error (ContentBean.AccountUserNotExise, 401);
    }

    public ResponseBean findPage(PageVo pageVo, HttpSession session) {
        QueryWrapper<User> wrapper = new QueryWrapper<> ();
        Page<User> page = new Page<> (pageVo.getCurrentPage (), pageVo.getPageSize ());

        if (StrUtil.isNotEmpty (pageVo.getQueryContent ())) {
            wrapper.like ("real_name", pageVo.getQueryContent ());
        }

        //排除当前登录账号
        String username = (String) session.getAttribute ("username");
        if (StrUtil.isNotEmpty (username)) {
            wrapper.ne ("username", username);
        }

        IPage<User> userIPage = userMapper.selectPage (page, wrapper);

        PageVo pv = new PageVo ();

        pv.setTotal (userIPage.getTotal ());

        List<User> userList = userIPage.getRecords ();

        pv.setData (userList);

        return ResponseBean.success (ContentBean.QuerySuccess, pv);
    }

    public ResponseBean updateRemark(Integer userId, String remark) {

        List<User> users = userMapper.selectList (null);
        for (User user : users) {
            if (user.getDelFlag () == 0) {
                user.setDelFlag (1);
                userMapper.updateById (user);
            }

        }

        Map map = new HashMap ();
        map.put ("userId", userId);
        map.put ("remark", remark);
        userMapper.updateRemark (map);
        return ResponseBean.success (ContentBean.UpdateSuccess);
    }

    public ResponseBean deleteById(Integer id) {
        userMapper.deleteById (id);

        return ResponseBean.success (ContentBean.DeleteSuccess);
    }

    public ResponseBean updateStatus(Integer id) {
        User user = userMapper.selectById (id);
        if (user.getStatus () == 0) {
            user.setStatus (1);
        } else {
            user.setStatus (0);
        }

        userMapper.updateById (user);

        return ResponseBean.success (ContentBean.OperationSuccess);
    }


    public ResponseBean writeNote(String content, HttpSession session) {
        String username = (String) session.getAttribute ("username");
        if (StrUtil.isNotEmpty (username)) {
            Map map = new HashMap ();
            map.put ("content", content);
            map.put ("username", username);
            userMapper.updateWriteNote (map);
        }

        return ResponseBean.success (ContentBean.UpdateSuccess);
    }

    public ResponseBean updatePass(UpdatePassVo updatePassVo, HttpSession session) {
        String username = (String) session.getAttribute ("username");
        QueryWrapper<User> wrapper = new QueryWrapper<> ();
        wrapper.eq ("username", username).eq ("password", updatePassVo.getOldPass ());
        User user = userMapper.selectOne (wrapper);
        if (ObjectUtil.isEmpty (user)) {
            return ResponseBean.error (ContentBean.UpdateEoor, 301);
        }

        //发送邮件
        asyncService.sendMail ();

        user.setPassword (updatePassVo.getNewPass ());
        userMapper.updateById (user);

        return ResponseBean.success (ContentBean.UpdateSuccess);
    }


}
